package spring.DI.methodDI;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 方法注入测试类:
 *       单例Bean 依赖原型Bean时, 一般配置是取不到 原型Bean的, 如何实现?
 *
 * @author ME
 * @date 2019/2/26 18:01
 */
public class TestMethodDI {

    @Test
    public void testLookup() {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeansConfig.class);
        Animal animal1 = applicationContext.getBean("animal", Animal.class);
        Animal animal2 = applicationContext.getBean("animal", Animal.class);
        Assert.assertSame("Animal 是 单例的（Singleton），所以 animal1 和 animal2 是同一对象", animal1, animal2);

        // TODO @Autowired 方式无法取到 原型bean
        Dog dog1 = animal1.getDog();
        Dog dog2 = animal1.getDog();
        Assert.assertSame("Animal 是 单例的，自动注入的 Dog 也被缓存了，所以 dog1、dog2 是同一对象", dog1, dog2);

        // 注意:这里是通过 createDog() 获取
        Dog dog3 = animal1.createDog();
        Dog dog4 = animal1.createDog();
        Assert.assertNotSame("使用了 lookup-method 注入多例，所以 cat1、cat2 不是同一对象", dog3, dog4);

        Animal2 animal22 = applicationContext.getBean(Animal2.class);
        Dog dog222 = animal22.createDog();
        Dog dog2221 = animal22.createDog();
        Assert.assertNotSame("使用了 lookup-method 注入多例，所以 cat1、cat2 不是同一对象", dog222, dog2221);
    }

    @Test
    public void testConstructor() {
        // -Dmy.property=sysProp
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
        context.setConfigLocation("beans.xml");
        context.refresh();

        Dog dog11 = context.getBean("dog11", Dog.class);
        System.out.println("dog11: " + dog11.toString());

        Dog dog12 = context.getBean("dog12", Dog.class);
        System.out.println("dog12: " + dog12.toString());

        Dog dog13 = context.getBean("dog13", Dog.class);
        System.out.println("dog13: " + dog13.toString());

        // try {
        //     Class dog = Class.forName("com.me.Dog");
        //     Constructor[] constructors = dog.getDeclaredConstructors();
        //     Arrays.stream(constructors).forEach(System.out::println);
        //
        // } catch (ClassNotFoundException e) {
        //     e.printStackTrace();
        // }

        String[] upParams = new String[]{"123"};
        for(int i = 0;i < upParams.length; i++) {upParams[i] = '\'' + upParams[i] + '\'';}
    }

}
